import React from 'react'
import { connect } from 'react-redux'
import { List, Badge } from 'antd-mobile'

@connect(
  state => state
)
class Msg extends React.Component {
  getLast (arr) {
    return arr[arr.length - 1]
  }
  render () {
    let Item = List.Item
    let Brief = Item.Brief
    let userid = this.props.user._id
    // 按照聊天用户分组，根据 chatid
    if (!this.props.chat.chatmsg.length) {
      return <p style={{textAlign: 'center'}}>暂无聊天信息</p>
    }
    let msgGroup = {}
    this.props.chat.chatmsg.forEach(v => {
      msgGroup[v.chatid] = msgGroup[v.chatid] || []
      msgGroup[v.chatid].push(v)
    })
    // console.log(msgGroup)
    let chatList = Object.values(msgGroup).sort((a, b) => {
      let a_last = this.getLast(a).ctime
      let b_last = this.getLast(b).ctime
      return b_last - a_last
    })
    // console.log(chatList)
    return (
      <div>
          {chatList.map(v => {
            let lastItem = this.getLast(v)
            let targetId = lastItem.from === userid ? lastItem.to : lastItem.from
            let name = this.props.chat.users[targetId] ? this.props.chat.users[targetId].name : ''
            let avatar = this.props.chat.users[targetId] ? this.props.chat.users[targetId].avatar : 'boy'
            let unreadNum = v.filter(item => !item.read && item.to === userid).length
            return (
              <List key={lastItem._id}>
                <Item thumb={require(`../../assets/image/${avatar}.png`)} extra={<Badge text={unreadNum}/>} arrow='horizontal' onClick={() => {this.props.history.push(`/chat/${targetId}`)}}>
                  {lastItem.content}
                  <Brief>{name}</Brief>
                </Item>
              </List>
            )
          })}
      </div>
    )
  }
}

export default Msg